package com.mldong.listener;

import cn.hutool.db.DbUtil;
import cn.hutool.db.Entity;
import cn.hutool.db.SqlConnRunner;
import cn.hutool.log.Log;
import com.mldong.context.constant.ConstantContext;
import org.springframework.boot.context.event.ApplicationContextInitializedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.core.Ordered;
import org.springframework.core.env.ConfigurableEnvironment;

import java.sql.Connection;
import java.sql.DriverManager;
import java.util.List;

/**
 * 常量初始化监听器
 */
public class ConstantsInitListener implements ApplicationListener<ApplicationContextInitializedEvent>, Ordered {
    @Override
    public void onApplicationEvent(ApplicationContextInitializedEvent applicationContextInitializedEvent) {
        ConfigurableEnvironment environment = applicationContextInitializedEvent.getApplicationContext().getEnvironment();
        // 获取数据库连接配置
        String dataSourceUrl = environment.getProperty("spring.datasource.url");
        String dataSourceUsername = environment.getProperty("spring.datasource.username");
        String dataSourcePassword = environment.getProperty("spring.datasource.password");
        String driverClassName = environment.getProperty("spring.datasource.driver-class-name");
        try{
            Class.forName(driverClassName);
            Connection connection = DriverManager.getConnection(dataSourceUrl,dataSourceUsername, dataSourcePassword);
            SqlConnRunner sqlConnRunner = DbUtil.newSqlConnRunner(connection);
            List<Entity> list = sqlConnRunner.findAll(connection,Entity.create("sys_config")
                    .set("enabled", 1)
                    .set("is_deleted",0));
            list.forEach(item->{
                String code = item.getStr("code");
                String content = item.getStr("content");
                ConstantContext.putConstant(code,content);
                Log.get().info("加载常量：{}={}",code, content);
            });
        } catch (Exception e){

            e.printStackTrace();
        }

    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE;
    }
}
